package com.yanqu.road.server.cmd.tradewar.cross;

import com.yanqu.road.entity.enums.eTradeWarBattleType;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.pb.cross.tradewar.CrossTradeWarProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.player.TradeWarModule;
import com.yanqu.road.server.manger.ForbiddenMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;

import java.util.ArrayList;
import java.util.List;

@Cmd(code = Protocol.S_CROSS_TRADE_WAR_BATTLE_PREPARE, desc = "跨服商战上阵准备")
public class CrossTradeWarBattlePrepareCmd extends AbstractCommand {
	private int activityId;
	private int battleType;
	private List<Integer> patronsIdList;
	private long enemyUserId;
	private long enemyServerId;
	private String battleUid;
	private int useItemId;

	@Override
	public boolean parseData(YanQuMessage packet) throws Exception {
		CrossTradeWarProto.CrossTradeWarBattleReqMsg reqMsg = CrossTradeWarProto.CrossTradeWarBattleReqMsg.parseFrom(packet.getBytes());
		activityId = reqMsg.getActivityId();
		battleType = reqMsg.getBattleType();
		patronsIdList = new ArrayList<>();
		for(Integer patronsId : reqMsg.getPatronsIdListList()){
			if(!patronsIdList.contains(patronsId)){
				patronsIdList.add(patronsId);
			}
		}
		enemyUserId = reqMsg.getEnemyUserId();
		enemyServerId = reqMsg.getEnemyServerId();
		battleUid = reqMsg.getBattleUid();
		useItemId = reqMsg.getUseItemId();
		return true;
	}

	@Override
	public void execute(GamePlayer player, YanQuMessage packet) throws Exception {

		if(eTradeWarBattleType.Track.getValue() == battleType) {
			if (ForbiddenMgr.isForbiddenCmd(player.getUserId(), Protocol.S_CROSS_TRADE_WAR_BATTLE_PREPARE)) {
				ret = GameErrorCode.E_SYSTEM_NO_OPEN;
				return;
			}
		}

		if (patronsIdList.size() == 0 || patronsIdList.size() > GameConfig.CROSS_TRADE_WAR_MAX_BATTLE_PATRONS_COUNT) {
			ret = GameErrorCode.E_TRADE_WAR_PATRONS_COUNT_ERROR;
			return;
		}

		if (enemyUserId != 0){
			if (GameUnionActivityGroupMgr.getGroupId(activityId,player.getUserId())!=GameUnionActivityGroupMgr.getGroupId(activityId,enemyUserId)){
				ret = GameErrorCode.E_UNION_ACTIVITY_NO_SAME_GROUP;
				return;
			}
		}
		ret = player.getModule(TradeWarModule.class).crossPrepare(activityId, battleType, patronsIdList, enemyUserId, enemyServerId, battleUid, useItemId);
	}

	@Override
	public void sendData(GamePlayer player) {
		if(0 != ret) {
			CrossTradeWarProto.CrossTradeWarBattleRespMsg.Builder respMsg = CrossTradeWarProto.CrossTradeWarBattleRespMsg.newBuilder();
			respMsg.setRet(ret);
			player.sendPacket(Protocol.U_CROSS_TRADE_WAR_BATTLE_PREPARE, respMsg);
		}
	}

}
